package cn.wolfcode.shop.filter;

import cn.wolfcode.shop.common.Result;
import cn.wolfcode.shop.feign.UserFeignApi;
import cn.wolfcode.shop.util.CookieUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class TokenRefreshFilter extends ZuulFilter {

    @Autowired
    private UserFeignApi userFeignApi;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;  // 过滤类型
    }

    @Override
    public int filterOrder() {
        return 0; //过滤链优先级
    }

    @Override
    public boolean shouldFilter() {
        // 判断时候有 cookie ，在判断 cookie 中是否有 token
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = CookieUtils.getCookieValue(request, CookieUtils.USERTOKEN_NAME);
        return !StringUtils.isEmpty(token);  // token 不为空的时候才放行
    }

    @Override
    public Object run() throws ZuulException {
        // 执行 token 刷新操作
        // 先通过上下文得到 值 token
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = CookieUtils.getCookieValue(request, CookieUtils.USERTOKEN_NAME);
        // 远程调用会员服务方法，完成token的刷新
        Result<Boolean> result = userFeignApi.refeshToken(token);
        if (!result.hasError()) {      //也是返回有三种情况
            // 刷新Cookie有效时间————》重新设置Cookie即可
            CookieUtils.addInCookie(ctx.getResponse(), CookieUtils.USERTOKEN_NAME, token);
        }
        return null;
    }
}
